package com.weixin.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public final class GsonUtil {

	private static String dateFormat = "yyyy-MM-dd HH:mm:ss";

	private GsonUtil() {

	}

	/**
	 * 对象转换为json
	 * 
	 */
	public static String toJson(Object info) {
		Gson gson = new GsonBuilder().setDateFormat(dateFormat).create();
		String result = "";
		try {
			result = gson.toJson(info);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 对象列表转换为json
	 * 
	 */
	public static String toJson(List<?> list) {
		Gson gson = new GsonBuilder().setDateFormat(dateFormat).create();
		String result = "";
		try {
			result = gson.toJson(list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * json字符串转换为对象
	 * 
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Object fromJson(String jsonStr, Class clazz) {
		Gson gson = new GsonBuilder().setDateFormat(dateFormat).create();
		Object object = null;
		try {
			object = gson.fromJson(jsonStr, clazz);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return object;
	}
	
	
	/**
	 * json字符串转换为对象
	 * 
	 */
	public static Object fromJson(String jsonStr, java.lang.reflect.Type type) {
		Gson gson = new GsonBuilder().setDateFormat(dateFormat).create();
		Object object = null;
		try {
			object = gson.fromJson(jsonStr,type);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return object;
	}


	/**
	 * 对象转化成Map<String, String>
	 * 
	 */
	public static Map<String, String> toJsonMap(Object info) {
		Map<String, String> results = new HashMap<String, String>();
		Gson gson = new GsonBuilder().setDateFormat(dateFormat).create();
		String jsonStr = "";
		try {
			if (info instanceof String) {
				jsonStr = (String) info;
			} else {
				jsonStr = gson.toJson(info);
			}
			Map<String, String> tmpMap = gson.fromJson(jsonStr, new TypeToken<Map<String, String>>() {
			}.getType());
			results.putAll(tmpMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return results;
	}
	
	public static Map<String, Object> toJsonObjectsMap(Object info) {
		Map<String, Object> results = new HashMap<String, Object>();
		Gson gson = new GsonBuilder().setDateFormat(dateFormat).create();
		String jsonStr = "";
		try {
			if (info instanceof String) {
				jsonStr = (String) info;
			} else {
				jsonStr = gson.toJson(info);
			}
			Map<String, Object> tmpMap = gson.fromJson(jsonStr, new TypeToken<Map<String, Object>>() {
			}.getType());
			results.putAll(tmpMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return results;
	}
	
}
